import { http } from "@/utils/http";
import type { ApiResponse } from "../../user";
import { ensureArray, normalisePagination, toNumber } from "@/api/_helpers";

const MEMBER_BASE = "/system/org/members";

export const MEMBER_ROLE_OPTIONS = [
  { label: "负责人", value: "owner" },
  { label: "管理员", value: "admin" },
  { label: "成员", value: "member" }
];

export const MEMBER_STATUS_OPTIONS = [
  { label: "禁用", value: 0 },
  { label: "启用", value: 1 }
];

export const ORG_TYPE_OPTIONS = [
  { label: "卖家组织", value: "seller" },
  { label: "买家组织", value: "buyer" },
  { label: "买卖兼营", value: "both" }
];

export interface OrgMemberFilterParams {
  page?: number;
  page_size?: number;
  org_id?: number | string;
  user_id?: number | string;
  member_role?: string;
  status?: number | string;
  org_type?: string;
}

export interface OrgMemberItem {
  id: number;
  org_id: number;
  user_id: number;
  member_role: string;
  position?: string;
  status: number;
  invited_by: number | null;
  joined_at: string | null;
  create_time?: string;
  update_time?: string;
  org?: {
    id: number;
    name: string;
    org_type: string;
  } | null;
  user?: Record<string, any> | null;
}

export interface OrgMemberListResult {
  list: OrgMemberItem[];
  pagination: {
    total: number;
    pageSize: number;
    currentPage: number;
  };
}

const mapMember = (item: Record<string, any>): OrgMemberItem => ({
  id: toNumber(item.id, 0),
  org_id: toNumber(item.org_id, 0),
  user_id: toNumber(item.user_id, 0),
  member_role: item.member_role ?? "member",
  position: item.position ?? "",
  status: toNumber(item.status, 0),
  invited_by: item.invited_by !== null ? toNumber(item.invited_by, null) : null,
  joined_at: item.joined_at ?? null,
  create_time: item.create_time ?? "",
  update_time: item.update_time ?? "",
  org: item.org
    ? {
        id: toNumber(item.org.id, 0),
        name: item.org.name ?? "",
        org_type: item.org.org_type ?? ""
      }
    : null,
  user: item.user ?? null
});

export const fetchMemberList = async (
  params: OrgMemberFilterParams = {}
): Promise<OrgMemberListResult> => {
  const page = toNumber(params.page, 1) || 1;
  const pageSize = toNumber(params.page_size, 10) || 10;

  const res = await http.request<ApiResponse<any>>("get", MEMBER_BASE, {
    params: {
      ...params,
      page,
      page_size: pageSize
    }
  });

  const payload = (res?.data ?? {}) as Record<string, any>;
  const list = ensureArray<Record<string, any>>(
    payload.list ?? payload.data ?? []
  ).map(mapMember);
  const pagination = normalisePagination(
    payload.pagination ?? payload,
    page,
    pageSize,
    list.length
  );

  return {
    list,
    pagination
  };
};

export const fetchMemberDetail = async (
  id: number | string
): Promise<OrgMemberItem> => {
  const res = await http.request<ApiResponse<any>>(
    "get",
    `${MEMBER_BASE}/${id}`
  );
  return mapMember(res.data ?? {});
};

export const createMember = async (payload: Record<string, any>) => {
  return http.request<ApiResponse<any>>("post", MEMBER_BASE, {
    data: payload
  });
};

export const updateMember = async (
  id: number | string,
  payload: Record<string, any>
) => {
  return http.request<ApiResponse<any>>("put", `${MEMBER_BASE}/${id}`, {
    data: payload
  });
};

export const deleteMember = async (id: number | string) => {
  return http.request<ApiResponse<boolean>>("delete", `${MEMBER_BASE}/${id}`);
};

export default {
  fetchList: fetchMemberList,
  fetchDetail: fetchMemberDetail,
  create: createMember,
  update: updateMember,
  remove: deleteMember
};
